package web.dao.impls;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import map.beans.OwfLibLocationBean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import web.dao.interfaces.OwfLibLocationDao;

@Repository("owfLibLocDao")
@Transactional(readOnly = true)
public class OwfLibLocationDaoImpl implements OwfLibLocationDao {
	private static Logger LOGGER = LoggerFactory.getLogger(OwfLibLocationDaoImpl.class);
	private final int FIRST = 0;
	
	@PersistenceContext
	private EntityManager entityManager;
	

	@Override
	@Transactional
	public List<OwfLibLocationBean> findAll() {
		TypedQuery<OwfLibLocationBean> query = entityManager.createQuery("SELECT t FROM OwfLibLocationBean t ORDER BY t.id", OwfLibLocationBean.class);
		return query.getResultList();
	}

	@Override
	public Long save(OwfLibLocationBean owf) {
		try {
			System.out.println("........... Persisting Object  " + owf.getId() + ": " + owf.getLibLocation() + "  ..............");

			entityManager.persist(owf);
			entityManager.flush();
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
		return owf.getId();
	}

	@Override
	public Long update(OwfLibLocationBean owf) {
		try {
			System.out.println("........... Updating Object " + owf.getId() + ": " + owf.getLibLocation() + "  .............."); 
			entityManager.merge(owf);
			entityManager.flush();
		} catch (Exception e) {
			e.printStackTrace();		
		}
		return owf.getId();
	}

	@Override
	public boolean delete(OwfLibLocationBean owf) {
		// check that it exists in the DB
		owf = entityManager.getReference(OwfLibLocationBean.class, owf.getId());
		boolean status = false;
		
		if (owf != null) {					
			entityManager.remove(owf);
			entityManager.flush();
			status = true;
		}
		return status;
	}

	@Override
	public OwfLibLocationBean getOwfLibLocationBean() {
		List<OwfLibLocationBean> owfList = findAll();
		OwfLibLocationBean owf = owfList.isEmpty() ? null : owfList.get(FIRST);
		return owf;
	}

}
